<template>
	<view class="container">
    <view class="flex justify-start padding-top" style="width: 100%;">
      <view class="padding-top-xl padding-left-sm" style="height: 200upx;">
        <image
          src="/src/static/zr/back.png"
          mode=""
          style="width: 60upx; height: 60upx;"
          @click="handelBack"
        />
      </view>
    </view>
		<view class="text-center">
			<image class="round margin-top" 
				:src="tempUserInfo.avatar ? tempUserInfo.avatar : '/src/static/logo.png'" 
				mode="aspectFill"
			></image>

			<view class="margin text-xl">
				<button class="cu-btn bg-gradual-purple" @click="handleAvatar">点击修改头像</button>
			</view>
		</view>
		<view class="padding-lr margin-lr">
			<view class="margin-tb padding-lr">
				用户名
			</view>
			<custom-input v-model="tempUserInfo.name" holder="请输入用户名">
				<text class="iconfont icon-wode"></text>
			</custom-input>
		</view>
		<view class="padding-lr margin-lr">
			<view class="margin-tb padding-lr">
				心途账号
			</view>
			<custom-input v-model="tempUserInfo.phone" holder="请输入心途账号">
				<text class="iconfont icon-shuqian"></text>
			</custom-input>
		</view>

		<view class="padding margin-top flex justify-around">
			<button class="cu-btn bg-gray block" @click="resetTempInfo">取消</button>
			<button class="cu-btn bg-gradual-purple block" @click="handleUpdate">保存</button>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useAccount } from '@/store/user';
import { userUpdate } from '@/api/user';

const account = useAccount();
// 临时存储用户信息
const tempUserInfo = ref({
  name: account.userinfo.name,
  phone: account.userinfo.phone,
  avatar: account.userinfo.avatar
});

// 标记是否有未保存的修改
const hasUnsavedChanges = ref(false);

// 监听临时信息变化
const watchTempUserInfo = () => {
  if (tempUserInfo.value.name !== account.userinfo.name ||
      tempUserInfo.value.phone !== account.userinfo.phone ||
      tempUserInfo.value.avatar !== account.userinfo.avatar) {
    hasUnsavedChanges.value = true;
  } else {
    hasUnsavedChanges.value = false;
  }
};

// 监听临时信息变化
watchTempUserInfo();

// 重置临时信息
const resetTempInfo = () => {
  tempUserInfo.value = {
    name: account.userinfo.name,
    phone: account.userinfo.phone,
    avatar: account.userinfo.avatar
  };
  hasUnsavedChanges.value = false;
};

// 更新用户信息
const handleUpdate = async () => {
  let title = '更新成功';
  try {
    const { objectId, sessionToken } = account.userinfo;
    const res = await userUpdate(objectId, sessionToken, tempUserInfo.value);
    // 仅在更新成功后更新本地数据
    account.userinfo.name = tempUserInfo.value.name;
    account.userinfo.phone = tempUserInfo.value.phone;
    account.userinfo.avatar = tempUserInfo.value.avatar;
    uni.setStorageSync('userinfo', account.userinfo);
    hasUnsavedChanges.value = false;
    console.log('更新成功', res);
  } catch (error) {
    title = '更新失败';
    console.error('更新失败', error);
  }
  uni.showToast({
    title,
    icon: 'none'
  });
};

// 文件上传
const handleAvatar = () => {
  uni.chooseImage({
    count: 1,
    success: async (file) => {
      const temp = file.tempFilePaths[0];
      tempUserInfo.value.avatar = temp;
      hasUnsavedChanges.value = true;
      uni.uploadFile({
        url: 'http://1.95.51.46:3000/upload',
        filePath: temp,
        name: 'avatar',
        success: (res) => {
          console.log(res.data);
          try {
            const url = JSON.parse(res.data).url;
            tempUserInfo.value.avatar = url;
            hasUnsavedChanges.value = true;
          } catch (parseError) {
            console.error('解析上传结果失败', parseError);
          }
        },
        fail: (err) => {
          console.error('头像上传失败', err);
        }
      });
    },
    fail: (err) => {
      console.error('选择图片失败', err);
    }
  });
};

const handelBack = () => {
  if (hasUnsavedChanges.value) {
    uni.showModal({
      title: '提示',
      content: '您有未保存的信息，确定要离开吗？',
      success: (res) => {
        if (res.confirm) {
          uni.navigateBack({ delta: 1 });
        }
      }
    });
  } else {
    uni.navigateBack({ delta: 1 });
  }
};
</script>

<style lang="scss">
.container{
	 background-image: 
	    linear-gradient(90deg, #f5eff1 0%, #e3e1fd 100%),  /* 横向渐变 */
	    linear-gradient(to bottom, rgba(247,247,247,0) 0%, rgba(247,247,247,0.85) 100%);  /* 垂直渐变（透明度变化） */
	  
	  /* 混合模式：让两个渐变融合显示 */
	  background-blend-mode: overlay;
	  
	  height: 100%; /* 顶部渐变区域高度 */
	  width: 100%;
}
page {
  background-color: white;
  image {
    width: 200upx; 
    height: 200upx; 
  }
}
</style>